//
//  NetWorkResquestTool.m
//  Timingbar
//
//  Created by zibin on 2017/7/17.
//  Copyright © 2017年 timingbar. All rights reserved.
//

#import "NetWorkResquestTool.h"
#import "NetworkSessionManger.h"
#define netWorkDefaultMessage @"服务器努力抢救中，请稍后再试"
#import <AFNetworking/AFNetworking.h>


static NetworkSessionManger *_resquestManger;

@interface NetWorkResquestTool()

@property (nonatomic, strong) Class responseClass;
@property (nonatomic, assign) NSInteger count;
@end

@implementation NetWorkResquestTool

+ (NetworkSessionManger *)shareResquestManger
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(_resquestManger == nil)
            _resquestManger = [NetworkSessionManger manager];
        
           //请求json
          _resquestManger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             @"text/html",
                                                             @"image/jpeg",
                                                             @"text/plain",
                                                             @"image/png",
                                                             @"application/octet-stream",
                                                             @"text/json",
                                                             nil];
        
        //无条件的信任服务器上的证书
        AFSecurityPolicy *securityPolicy =[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        
        // 客户端是否信任非法证书
        securityPolicy.allowInvalidCertificates = YES;
        
        // 是否在证书域字段中验证域名
        securityPolicy.validatesDomainName = NO;
        
        _resquestManger.securityPolicy = securityPolicy;
    });
    return _resquestManger;
}

- (instancetype)init
{
  if(self = [super init])
  {
      //设置默认值
      self.timeOut = 60.0;
      self.responseQueue = dispatch_get_main_queue();
      self.responseDataType = NetWorkResponseDataType_Default;
  }
    return self;
}

#pragma mark - 网络请求
#pragma mark - 网络请求
- (NSURLSessionDataTask *)httpGetWithModel:(BaseResquestModel *)requestModel
                             ResponseClass:(Class)responseClass
                            sucessResponse:(sucessResponseBlock)sucessBlock
                              failResponse:(failResponseBlock)failBlock
{
    [self resquestProcess:requestModel responseClass:responseClass];
    
    return [self baseGetHttpWithURL:requestModel.url parameters:[requestModel modelToBaseResquestModel] sucessResponse:sucessBlock failResponse:failBlock];
}

- (NSURLSessionDataTask *)httpPUTWithModel:(BaseResquestModel *)requestModel
                             ResponseClass:(Class)responseClass
                            sucessResponse:(sucessResponseBlock)sucessBlock
                              failResponse:(failResponseBlock)failBlock
{
    [self resquestProcess:requestModel responseClass:responseClass];
    
    return [self basePUTHttpWithURL:requestModel.url parameters:[requestModel modelToBaseResquestModel] sucessResponse:sucessBlock failResponse:failBlock];
}

- (NSURLSessionDataTask *)httpPostWithModel:(BaseResquestModel *)requestModel
                              ResponseClass:(Class)responseClass
                             sucessResponse:(sucessResponseBlock)sucessBlock
                               failResponse:(failResponseBlock)failBlock
{
    [self resquestProcess:requestModel responseClass:responseClass];
    return [self basePostHttpWithURL:[requestModel url] parameters:[requestModel modelToBaseResquestModel] sucessResponse:sucessBlock failResponse:failBlock];
}

- (void)resquestProcess:(BaseResquestModel *)requestModel responseClass:(Class)responseClass
{
    _resquestModel = requestModel;
    self.responseClass= responseClass;
}

#pragma mark - 基础网络请求
- (NSURLSessionDataTask *)baseGetHttpWithURL:(NSString *)url
                                  parameters:(NSDictionary *)paramDicts
                              sucessResponse:(sucessResponseBlock)sucessBlock
                                failResponse:(failResponseBlock)failBlock{
    
    NetworkSessionManger *httpManger = [self configHttpBaseInfoWithURL:url withParamsDict:paramDicts httpType:@"GET-请求方式"];
    //包装URL
    NSString *resquestURL = [self apendGetParamStringWithDictionary:paramDicts withURL:url];
    
    NSString *resultURL = [resquestURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionDataTask *task = [httpManger GET:resultURL parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        [self resultProcess:responseObject error:nil sucessResponse:sucessBlock failResponse:failBlock];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self resultProcess:nil error:error sucessResponse:sucessBlock failResponse:failBlock];
    }];
    return task;
}

- (NSURLSessionDataTask *)basePUTHttpWithURL:(NSString *)url
                                  parameters:(NSDictionary *)paramDicts
                              sucessResponse:(sucessResponseBlock)sucessBlock
                                failResponse:(failResponseBlock)failBlock
{
    NetworkSessionManger *httpManger = [self configHttpBaseInfoWithURL:url withParamsDict:paramDicts httpType:@"PUT请求方式"];
    NSURLSessionDataTask *task = [httpManger PUT:url parameters:paramDicts success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self resultProcess:responseObject error:nil sucessResponse:sucessBlock failResponse:failBlock];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self resultProcess:nil error:error sucessResponse:sucessBlock failResponse:failBlock];
    }];
    return task;
}

- (NSURLSessionDataTask *)basePostHttpWithURL:(NSString *)url
                                   parameters:(NSDictionary *)paramDicts
                               sucessResponse:(sucessResponseBlock)sucessBlock
                                 failResponse:(failResponseBlock)failBlock
{
    NetworkSessionManger *httpManger = [self configHttpBaseInfoWithURL:url withParamsDict:paramDicts httpType:@"post请求方式"];
    NSURLSessionDataTask *task = [httpManger POST:url parameters:paramDicts success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        [self resultProcess:responseObject error:nil sucessResponse:sucessBlock failResponse:failBlock];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self resultProcess:nil error:error sucessResponse:sucessBlock failResponse:failBlock];
    }];
    return task;
}
- (NetworkSessionManger *)configHttpBaseInfoWithURL:(NSString *)url withParamsDict:(NSDictionary *)paramDicts  httpType:(NSString *)typeSting
{
    //检测URL
    url = [self checkResquestURLWithURL:url];
    NSLog(@"request-info:\n{\n requestType:%@\n url:%@\n params:%@\n}",typeSting,url,paramDicts);
    
    //设置请求基本信息
    NetworkSessionManger *httpManger = [NetWorkResquestTool shareResquestManger];
    if(![self.responseQueue isEqual:dispatch_get_main_queue()])
        httpManger.completionQueue = self.responseQueue;
    httpManger.requestSerializer.timeoutInterval = self.timeOut;
    
    //增加请求头
   // [self addResquestHeadDictionary:self.resquestDefaultHeadDict WithRequestSerializer:httpManger.requestSerializer];
    
    return httpManger;
}

#pragma mark- 请求结果处理
- (void)resultProcess:(id)responseDict
                error:(NSError *)error
       sucessResponse:(sucessResponseBlock)sucessBlock
         failResponse:(failResponseBlock)failBlock
{
  if(error != nil)  //请求未连接的失败
    {
        NSString *localMessage = error.userInfo[@"NSLocalizedDescription"];
        [self hanldeErrorMessage:localMessage code:NETWORK_LINK_ERROR_CODE failResponse:failBlock errorInfo:error.userInfo];
          return;
    }
   else if (responseDict == nil)  //请求失败，返回nil，服务器返回数据错误
    {
         NSString *localMessage = netWorkDefaultMessage;
        [self hanldeErrorMessage:localMessage code:NETWORK_LINK_ERROR_CODE failResponse:failBlock errorInfo:error.userInfo];
         return;
    }
   else  //请求成功
    {
        
        NSLog(@"响应返回的数据--------%@",responseDict);
        NSError *jsonError;
        _responseModel = [MTLJSONAdapter modelOfClass:self.responseClass fromJSONDictionary:responseDict error:&jsonError];
        if(_responseModel == nil||jsonError)
        {
            NSLog(@"\n序列化失败：%@",jsonError);
           [self hanldeErrorMessage:@"服务器正在解析中..." code:jsonError.code failResponse:failBlock errorInfo:jsonError.userInfo];
            return;
        }
        
        //解析完成
        if([_responseModel.status isEqualToString:@"1"])
        {
            _responseModel.success = YES;
            if(sucessBlock != nil)
            {
                dispatch_async(self.responseQueue, ^{
                    sucessBlock(self->_responseModel);
                });
            }
        } //登录不成功
        else if([_responseModel.status isEqualToString:@"3"])
        {
            ZB_LoginUserModel *user = [ZB_LoginUserDM currentLoginUser];
            user.loginStatus = ZB_LoginStatus_None;
            user.isLogin = NO;
            user.user_id = @"";
            user.token = @"";
            [[ZB_LoginUserDM shareInstance] saveCurrentUserInfoToCacheWithUser:user];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NOT_LOGIN_NOTIFATION" object:nil];
             [self hanldeErrorMessage:self.responseModel.message code:self.responseModel.code failResponse:failBlock errorInfo:error.userInfo];
            
        }else  //请求失败
        {
            [self hanldeErrorMessage:self.responseModel.message code:self.responseModel.code failResponse:failBlock errorInfo:error.userInfo];
        }
        
    }

}

- (void)hanldeErrorMessage:(NSString *)message code:(NSInteger)code failResponse:(failResponseBlock)failBlock errorInfo:(NSDictionary *)errorInfo
{
    if(message.length == 0)
        message = netWorkDefaultMessage;
   NSError *error = [NSError errorWithDomain:[NSString stringWithFormat:@"%@",message] code:code userInfo:errorInfo];
    _responseModel.success = NO;
    if(failBlock != nil)
    {
        dispatch_async(self.responseQueue, ^{
            failBlock(error);
        });
    }
}


#pragma mark- pravite
- (void)addResquestHeadDictionary:(NSDictionary *)headDict WithRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer
{
    [headDict enumerateKeysAndObjectsUsingBlock:^(NSString  *key, NSString  *obj, BOOL * _Nonnull stop) {
        if(key.length == 0 || obj.length == 0) *stop = YES;
        [requestSerializer setValue:obj forHTTPHeaderField:key];
    }];
}

- (NSString *)checkResquestURLWithURL:(NSString *)url
{
    if(url.length == 0)
    {
        NSLog(@"URL为空");
        return @"htttp://www.baidu.com";
    }
    else
    {
        return url;
    }
}

/**
 通过参数比较包装URL
 
 @param paramDicts 参数
 @param url get请求的主要URL
 @return url
 */
- (NSString *)apendGetParamStringWithDictionary:(NSDictionary *)paramDicts withURL:(NSString *)url
{
    __block NSInteger index = 0;
    __block NSString *resquestURL = url;
    [paramDicts enumerateKeysAndObjectsUsingBlock:^(NSString  *key,  id obj, BOOL * _Nonnull stop) {
        
        if(index == 0)
        {
            if(key.length != 0)
                resquestURL = [resquestURL stringByAppendingFormat:@"?%@=%@",key,obj];
        }
        else
        {    if(key.length != 0)
            resquestURL = [resquestURL stringByAppendingFormat:@"&%@=%@",key,obj];
        }
        index++;
        
    }];
    return resquestURL;
}

- (NSMutableDictionary *)resquestDefaultHeadDict
{
    if(_resquestDefaultHeadDict == nil)
    {
        _resquestDefaultHeadDict = [NSMutableDictionary dictionary];
    }
    return _resquestDefaultHeadDict;
}

- (Class)responseClass
{
    if(_responseClass == nil)
    {
        _responseClass = [BaseResponseModel class];
    }
    return _responseClass;
}




@end
